#!/usr/bin/env python
# Create: 2018/10/15
__author__ = '749B'
"""自动登录51CTO"""

import os
import pickle
from bs4 import BeautifulSoup

from utils.check_cache import get_pk_name
from utils.base64p import b64decode_str
from utils.session import MySession

session = MySession(__file__)
base_url = "http://home.51cto.com"


def get_login_page(url=None, pk=False):
    """爬取登录页面，返回页面对象"""
    url = url or "http://home.51cto.com/index"  # 登录页面
    pk_name = get_pk_name(__file__)
    response = None
    if os.path.exists(pk_name) and pk:  # 要拿csrf，不能用缓存
        print("已经爬取过了，获取缓存的内容...")
        with open(pk_name, 'rb') as f:
            response = pickle.load(f)

    # 只有在没有缓存过页面的时候才进行爬取
    if not response:
        response = session.get(url)
        # 爬完之后记得保存，下次就不用再去爬取了
        if pk:
            with open(pk_name, 'wb') as f:
                pickle.dump(response, f)

    return response


def create_form(r):
    """解析爬到的页面对象，返回form信息的字典"""
    soup = BeautifulSoup(r.text, features='html.parser')
    form = soup.find('form')
    inputs = form.find_all('input')
    form_data = {}
    for i in inputs:
        k = i.get('name')
        v = i.get('value')
        form_data[k] = v
    return {
        'action': form.attrs['action'],
        'method': form.attrs['method'],
        'data': form_data
    }


def auth_login(obj):
    """登录验证，提交form"""
    url = "%s%s" % (base_url, obj['action'])
    data = obj['data']
    # 获取密码
    with open('password/51cto.txt') as f:
        auth = f.read()
        auth = auth.split('\n')
    for i in data:
        if 'rememberMe' in i:
            data[i] = '0'
        if 'username' in i:
            data[i] = auth[0]
        if 'password' in i:
            data[i] = b64decode_str(auth[1])
    r = session.request(obj['method'], url, data=data)
    if r.text:
        exit("登录失败")
    print("登录成功")


def check():
    """获取用户名，验证登录"""
    url = 'http://edu.51cto.com/center/course/user/get-study-course'
    r = session.get(url)
    soup = BeautifulSoup(r.text, features='html.parser')
    name = soup.select('body div.name h2')
    if name:
        print("登录验证：", name[0].text.strip())
        return True
    else:
        print("登录验证失败...")
        return False


def login():
    """直接调用这个方法，完成登录
    然后导入这里的全局变量session，像下面这样：
    # from _51CTO import login
    # session = login.session
    """
    global session
    s = session.load()
    if s:
        session = s
        if check():
            return session
        else:
            session = MySession(__file__)
    r = get_login_page()
    o = create_form(r)
    auth_login(o)
    if check():
        session.save()
        return session
    else:
        exit("登录失败：%s" % __name__)


if __name__ == '__main__':
    print(session.cookies)
    login()
    print(session.cookies)



